<template>
  <div class="app-container shop-detail">
    <div class="business-info-mod">
      <el-form
        @submit.native.prevent
        ref="shopBasicInfo"
        label-width="140px"
        :model="shopBasicInfo"
        :rules="shopBasicInfoRules"
        size="small"
      >
        <div class="ci-wrapper">
          <div class="left-info">
            <!-- 门店编号 -->
            <el-form-item :label="$t('outlet.outletId')" prop="shopCode">
              <p class="txt">
                <el-input
                  v-model="shopBasicInfo.shopCode"
                  :placeholder="$t('shopProcess.onlyNumber')"
                  maxlength="20"
                  @blur="
                    shopBasicInfo.shopCode = shopBasicInfo.shopCode
                      ? removeHeadAndTailSpaces(shopBasicInfo.shopCode)
                      : shopBasicInfo.shopCode
                  "
                />
              </p>
            </el-form-item>
            <el-form-item :label="$t('outlet.outletName')" prop="shopName">
              <p class="txt">
                <el-input
                  v-model="shopBasicInfo.shopName"
                  :placeholder="$t('shopProcess.shopLimits2')"
                  maxlength="20"
                  @blur="
                    shopBasicInfo.shopName = shopBasicInfo.shopName
                      ? removeHeadAndTailSpaces(shopBasicInfo.shopName)
                      : shopBasicInfo.shopName
                  "
                />
              </p>
            </el-form-item>
            <el-form-item :label="$t('outlet.shopTypeText')" prop="shopType">
              <p class="txt">
                <el-select
                  filterable
                  v-model="shopBasicInfo.shopType"
                  :placeholder="$t('outlet.shopTypeText')"
                >
                  <el-option
                    v-for="item in shopTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </p>
            </el-form-item>

            <!-- 承租商名称 -->
            <el-form-item :label="$t('shopProcess.brandName')" prop="brandId">
              <p class="txt">
                <el-select
                  filterable
                  :filter-method="searchBrand"
                  v-model="shopBasicInfo.brandId"
                  :placeholder="$t('shopProcess.selectBrand')"
                  @focus="formInitiation"
                  @change="selectChange"
                >
                  <el-option
                    v-for="item in brandList"
                    :key="item.brandId"
                    :label="item.brandName"
                    :value="item.brandId"
                  >
                  </el-option>
                </el-select>
              </p>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <el-button
      class="confirm-btn"
      type="primary"
      size="small"
      @click="submitComplete"
      >{{ $t("brand.confirm") }}</el-button
    >
  </div>
</template>

<script>
  import { Debounce } from "@/utils/debounce";
  import { removeHeadAndTailSpaces } from "@/utils/validate";
  export default {
    directives: {
      "el-select-loadmore": {
        bind(el, binding) {
          // 获取element-ui定义好的scroll盒子
          const SELECTWRAP_DOM = el.querySelector(
            ".el-select-dropdown .el-select-dropdown__wrap"
          );
          SELECTWRAP_DOM.addEventListener("scroll", function () {
            /**
             * scrollHeight 获取元素内容高度(只读)
             * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
             * clientHeight 读取元素的可见高度(只读)
             * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
             * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
             */
            const condition =
              this.scrollHeight - this.scrollTop <= this.clientHeight + 0.5;
            if (condition) {
              binding.value();
            }
          });
        },
      },
    },
    components: {},
    data() {
      const validShopCode = (rule, value, callback) => {
        const reg = /[\W]/g;
        if (value && reg.test(value)) {
          return callback(new Error(this.$i18n.t("brand.tipsShopCode")));
        }
        callback();
      };
      return {
        removeHeadAndTailSpaces: removeHeadAndTailSpaces,
        // 店铺基本信息
        shopBasicInfo: {
          shopCode: "",
          shopName: "",
          shopType: "",
          brandId: "",
        },
        searchParam: {
          size: 999999,
          current: 1,
          brandName: "",
        },
        shopTagsListProps: {
          label: "name",
          value: "id",
          children: "secondShopTag",
        },
        shopTagsList: [], //商铺标签
        selectValue: [],
        brandTotal: "",

        shopTypeList: [
          {
            value: 1,
            label: this.$t("outlet.shopType1"),
          },
          {
            value: 2,
            label: this.$t("outlet.shopType2"),
          },
          {
            value: 3,
            label: this.$t("outlet.shopType3"),
          },
          {
            value: 4,
            label: this.$t("outlet.shopType4"),
          },
          {
            value: 5,
            label: this.$t("outlet.shopType5"),
          },
        ],
        brandList: [],
        shopBasicInfoRules: {
          shopCode: [
            {
              required: true,
              min: 2,
              // max: 20,
              message: this.$t("shopProcess.numberLimits"),
              trigger: "blur",
            },
            { validator: validShopCode, trigger: ["blur", "change"] },
          ],
          shopName: [
            {
              required: true,
              message: this.$t("shopProcess.shopNoNull"),
              trigger: "blur",
            },
            {
              min: 2,
              max: 20,
              message: this.$t("shopProcess.shopLimits2"),
              trigger: "blur",
            },
          ],
          shopType: [
            {
              required: true,
              message: this.$t("shopProcess.shopTypeNull"),
              trigger: "change",
            },
          ],
          brandId: [
            {
              required: true,
              message: this.$i18n.t("shopProcess.selectBrand"),
              trigger: "change",
            },
          ],
        },
      };
    },

    mounted() {},
    methods: {
      /**
       *  检索承租商名称
       * @param {String} val 检索字段
       */
      searchBrand(val) {
        if (this.timer) {
          clearTimeout(this.timer);
          this.timer = null;
        }
        this.timer = setTimeout(() => {
          this.emptySearchParam();
          if (val) {
            this.searchParam.brandName = val;
            this.getBrandList();
          } else {
            this.getBrandList();
          }
        }, 500);
      },
      /**
       * 下拉框触发焦点事件
       */
      formInitiation() {
        this.emptySearchParam();
        this.getBrandList();
      },
      /**
       * 初始化搜索数据
       */
      emptySearchParam() {
        this.searchParam.brandName = "";
        this.searchParam.size = 999999;
        this.searchParam.current = 1;
        this.brandList = [];
      },
      /**
       * 获取 连锁承租商 列表
       */
      getBrandList() {
        this.$http({
          url: this.$http.adornUrl("/platform/brand/page"),
          method: "get",
          params: this.$http.adornParams(
            Object.assign(this.searchParam, {
              // brandType: 0,
              // 承租商状态(-1:已删除 0: 停业中 1:营业中 2:平台下线 3:平台下线待审核 4:开店申请中 5:开店申请待审核)
              brandStatusList: [0, 1, 2, 3],
            })
          ),
        }).then(({ data }) => {
          if (!data) return;
          this.brandTotal = data.total;
          // this.brandList = [...this.brandList, ...data.records];
          this.brandList = data.records;
        });
      },
      /**
       * 选择承租商
       */
      selectChange() {
        // this.shopBasicInfo.brandId = this.selectValue;
      },
      loadmore() {
        this.searchParam.current++;
        if (this.brandList.length < this.brandTotal) {
          this.getBrandList();
        }
      },
      submitComplete: Debounce(function () {
        this.$refs["shopBasicInfo"].validate(async (valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl("/platform/shop/saveShopVirtual"),
              method: "post",
              data: this.$http.adornData(this.shopBasicInfo),
            }).then((res) => {
              console.log(res);
              if (res.code == "00000") {
                this.$message({
                  message: this.$t("shopProcess.submitTxt6"),
                  type: "success",
                });
                // 清空表单
                this.shopBasicInfo = {
                  shopCode: "",
                  shopType: "",
                  brandId: "",
                };
                this.$refs["shopBasicInfo"].resetFields();
              }
            });
          }
        });
      }, 1500),
    },
  };
</script>

<style lang="scss" scoped>
  .txt {
    width: 40%;
    min-width: 300px;
  }
  .el-select {
    width: 100%;
  }
  .el-cascader {
    width: 100%;
  }
  .confirm-btn {
    margin-left: 60px;
  }
</style>
